﻿using AutoMail.Models;
using AutoMail.Models.SettingDetails;
using Newtonsoft.Json;

namespace AutoMail.Tools
{
    public class MailSendConfigUtil
    {
        private readonly IConfiguration _configuration;
        private readonly SettingDetailsViewModel _settingSource;

        public MailSendConfigUtil(IConfiguration configuration)
        {
            // There's no DI
            _configuration = configuration;

            string settingFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, _configuration["EmailSendingSetting"]);
            if (System.IO.File.Exists(settingFilePath))
            {
                var settingsModel = JsonConvert.DeserializeObject<SettingDetailsViewModel>(System.IO.File.ReadAllText(settingFilePath));
                _settingSource = settingsModel;
            }
            
        }

        public MailSendServer GetMailSendServerInfo()
        {
            if (_settingSource != null)
            {
                return new MailSendServer() {
                    SmtpHost = _settingSource.SmtpHost,
                    SmtpPort = _settingSource.SmtpPort,
                    UserName = _settingSource.UserName,
                    Password = _settingSource.Password,
                    From = _settingSource.From,
                    Encoding = _settingSource.Encoding,
                    EnableSsl = _settingSource.EnableSsl
                };
            }

            return null;
        }

        public MailSendTimes GetMailSendTimesInfo()
        {
            if (_settingSource != null)
            {
                return new MailSendTimes()
                {
                    BirthdayMailSendTime = string.Join(' ', new string[] {
                        _settingSource.BirthdayMailSendTimeSecond.ToString().PadLeft(2, '0'),
                        _settingSource.BirthdayMailSendTimeMinute.ToString().PadLeft(2, '0'),
                        _settingSource.BirthdayMailSendTimeHour.ToString().PadLeft(2, '0'),
                    }),
                    AnniversaryMailSendTime = string.Join(' ', new string[]
                    {
                        _settingSource.AnniversaryMailSendTimeSecond.ToString().PadLeft(2, '0'),
                        _settingSource.AnniversaryMailSendTimeMinute.ToString().PadLeft(2, '0'),
                        _settingSource.AnniversaryMailSendTimeHour.ToString().PadLeft(2, '0'),
                    })
                };
            }

            return null;
        }
    }
}
